package cn.edu.zafu.bigdata.x.wupeng.g;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipeDemo1 {
    public static void main(String[] args) {
        new PipeDemo1().Test();
    }
    public void Test(){
        try{
            PipedInputStream pis = new PipedInputStream();
            PipedOutputStream pos = new PipedOutputStream(pis);

            Wtr wtr = new Wtr(pos);
            Rdr rdr = new Rdr(pis);

            wtr.start();
            rdr.start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class Wtr extends Thread{
        private PipedOutputStream writer;

        public Wtr(PipedOutputStream pos){
            writer = pos;
        }

        @Override
        public void run(){
            String s = "好好学习，天天向上";
            byte[] buf = s.getBytes();
            System.out.println("Send "+buf.length+" Bytes : "+s);
            try {
                writer.write(buf,0,buf.length);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("Send done");

        }


    }

    class Rdr extends Thread{
        private PipedInputStream reader;

        public Rdr(PipedInputStream pis){
            reader = pis;
        }

        @Override
        public void run(){
            ByteArrayOutputStream bis = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            try {
                len = reader.read(buf,0,1024);
                bis.write(buf,0,len);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("read "+len+"Bytes : "+bis.toString());
        }
    }
}
